package com.tea.modules.java8.thread.collections;

import com.tea.modules.java8.thread.annotation.ThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author jaymin
 * @since 2022/3/6 0:54
 */
@ThreadSafe
@Slf4j
public class CopyOnWriteArrayListDemo {
    /**
     * 请求总数
     */
    public static final int clientTotal = 5000;
    /**
     * 同时并发线程数
     */
    public static final int threadTotal = 200;
    public static List<Integer> list = new CopyOnWriteArrayList<>();

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal; i++) {
            int addI = i;
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    add(addI);
                    semaphore.release();
                } catch (InterruptedException | ParseException e) {
                    log.error("并发错误:", e);
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        log.info("size:{}", list.size());
    }

    /**
     * 线程安全
     * @param i
     * @throws ParseException
     */
    private static void add(int i) throws ParseException {
        list.add(i);
    }
}
